/*
题目链接 : https://leetcode.cn/problems/find-the-number-of-copy-arrays/description/
*/

//题解代码:

class Solution {
public:
    /*
        题目要求 copy[i]−copy[i−1]=original[i]−original[i−1]，那么有
        copy[1]−copy[0]=original[1]−original[0]
        copy[2]−copy[1]=original[2]−original[1]
        copy[3]−copy[2]=original[3]−original[2]
                          ⋮
        copy[i]−copy[i−1]=original[i]−original[i−1]
        左右累加得: copy[i]-copy[0] = original[i]−original[0] = d[i]
        d[i]是定值, 题目要求 ui<=copy[i]<=vi  ===>  ui-d[i]<=copy[0]<=vi-d[i]
        取所有copy[0]的交集就是答案
    */
    int countArrays(vector<int>& original, vector<vector<int>>& bounds) {
        int n = original.size();
        vector<int> d(n);
        for(int i=0;i<n;++i){
            d[i] = original[i] - original[0];
        }
        int ansl=-1,ansr=INT_MAX;
        int ans = INT_MAX;
        for(int i=0;i<n;++i){
            ansl = max(ansl,max(bounds[0][0],bounds[i][0]-d[i]));
            ansr = min(ansr,min(bounds[0][1],bounds[i][1]-d[i]));
        }
        return max(0,ansr-ansl+1);
    }
};
